package handler

import (
	"dev-proj-sys/modles"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}
	var data = modles.Article{
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := modles.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var articles []modles.Article
	modles.DB.Offset(offset).Limit(size).Find(&articles)

	var total int64
	modles.DB.Model(&modles.Article{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"data":  articles,
		"msg":   "查询成功",
		"total": total,
	})
	return
}
